Kotlin

Retrieving Collection Parts

Swift

Slice

                  ​
val numbers = listOf("one", "two", "three", "four", "five", "six")    
println(numbers.slice(1..3))
println(numbers.slice(0..4 step 2))
println(numbers.slice(setOf(3, 5, 0)))
                
                    ​
let numbers = listOf("one", "two", "three", "four", "five", "six")    
print(numbers.slice(1..3))
print(numbers.slice(0..4 step 2))
print(numbers.slice(setOf(3, 5, 0)))
                  

Take and drop

                  val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.take(3))
println(numbers.takeLast(3))
println(numbers.drop(1))
println(numbers.dropLast(5))
                
                    let numbers = listOf("one", "two", "three", "four", "five", "six")
print(numbers.take(3))
print(numbers.takeLast(3))
print(numbers.drop(1))
print(numbers.dropLast(5))
                  
                  val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.takeWhile { !it.startsWith('f') })
println(numbers.takeLastWhile { it != "three" })
println(numbers.dropWhile { it.length == 3 })
println(numbers.dropLastWhile { it.contains('i') })
                
                    let numbers = listOf("one", "two", "three", "four", "five", "six")
print(numbers.takeWhile { !it.startsWith('f') })
print(numbers.takeLastWhile { $0 != "three" })
print(numbers.dropWhile { it.length == 3 })
print(numbers.dropLastWhile { it.contains('i') })
                  

Chunked

                  val numbers = (0..13).toList()
println(numbers.chunked(3))
                
                    let numbers = (0..13).toList()
print(numbers.chunked(3))
                  
                  val numbers = (0..13).toList() 
println(numbers.chunked(3) { it.sum() })  // `it` is a chunk of the original collection
                
                    let numbers = (0..13).toList() 
print(numbers.chunked(3) { it.sum() })  // `it` is a chunk of the original collection
                  

Windowed

                  val numbers = listOf("one", "two", "three", "four", "five")    
println(numbers.windowed(3))
                
                    let numbers = listOf("one", "two", "three", "four", "five")    
print(numbers.windowed(3))
                  
                  val numbers = (1..10).toList()
println(numbers.windowed(3, step = 2, partialWindows = true))
println(numbers.windowed(3) { it.sum() })
                
                    let numbers = (1..10).toList()
print(numbers.windowed(3, step = 2, partialWindows = true))
print(numbers.windowed(3) { it.sum() })
                  
                  val numbers = listOf("one", "two", "three", "four", "five")    
println(numbers.zipWithNext())
println(numbers.zipWithNext() { s1, s2 -> s1.length > s2.length})
                
                    let numbers = listOf("one", "two", "three", "four", "five")    
print(numbers.zipWithNext())
print(numbers.zipWithNext() { s1, s2 -> s1.length > s2.length})